#from requests.packages.urllib3.exceptions import InsecureRequestWarning
import requests
import pandas as pd
import time
import os
from datetime import datetime
import json
import re
# from openpyxl import Workbook
from concurrent.futures import ThreadPoolExecutor

file_path = "D:/gugugu/自制早盘系统/开盘啦数据/"  # 修改为你希望保存文件的文件夹路径
file_name_ws = f"板块.xlsx"
file_name_cs = f"个股.xlsx"
save_path_ws = os.path.join(file_path, file_name_ws)
save_path_cs = os.path.join(file_path, file_name_cs)

#requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()

def fetch_data(BKNu):
    url1 = "https://apphq.longhuvip.com/w1/api/index.php"
    # url2 = "https://apphis.longhuvip.com/w1/api/index.php"
    hd = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Connection": "Keep-Alive", "Host": "",
          "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G977N Build/LMY48Z)", "Accept-Encoding": "gzip"}
    d1 = {"Order": "1", "a": "RealRankingInfo", "st": "30", "apiv": "w36", "Type": "1", "c": "ZhiShuRanking",
          "PhoneOSNew": "1", "DeviceID": "3c18c58d-8617-3b2b-9fb3-5ac2f73394a9",
          "VerSion": "5.14.0.0", "ZSType": "7", "Index": ""}

    d2 = {"Order": "1",
          "a": "ZhiShuStockList_W8",
          "st": "30",
          "apiv": "w36",
          "Type": "6",
          "c": "ZhiShuRanking",
          "PhoneOSNew": "1",
          "old": "1",
          "DeviceID": "3c18c58d-8617-3b2b-9fb3-5ac2f73394a9",
          "VerSion": "5.14.0.0",
          "IsZZ": "0",
          "Token": "0",
          "IsKZZType": "0",
          'UserID': "0",
          'PlateID': "",
          "Index": ""}

    hd["Host"] = "apphq.longhuvip.com"

    ws = pd.DataFrame(columns=["板块代码", "板块名称", "板块强度", "主力净额", "B300W净额"])
    cs = pd.DataFrame(columns=["股票代码", "股票名称", "价格", "涨幅", "板块细分", "实际流通"])
    all_stocks = pd.DataFrame(columns=["股票代码", "股票名称", "价格", "涨幅", "板块细分"])
    mid_stocks = pd.DataFrame(columns=["股票代码", "股票名称", "价格", "涨幅", "板块细分", "板块名称"])
    for BKNu in range(1):
        BK = BKNu * 30
        d1["Index"] = str(BK)
        rep = requests.post(url1, headers=hd, data=d1, verify=False)
        BK_data = json.loads(rep.text)
        if not BK_data['list']:  # 如果list列表为空
            break  # 跳出循环
        for idx1, item1 in enumerate(BK_data['list'], start=1):
            板块代码 = item1[0]
            板块名称 = item1[1]
            板块强度 = item1[2]
            主力净额 = item1[6] / 1000000000
            # 主力净额 = 主力净额.round(2)
            B300W净额 = item1[12] / 1000000000
            plate_stocks = pd.DataFrame(columns=["股票代码", "股票名称", "价格", "涨幅", "板块细分", "板块名称"])

            # T300W净额 = T300W净额.round(2)

            ws = pd.concat([ws, pd.DataFrame(
                {"板块代码": [板块代码], "板块名称": [板块名称], "板块强度": [板块强度], "主力净额": [主力净额],
                 "B300W净额": [B300W净额]})])
            # print(ws)
            for GGNu in range(1):
                GG = GGNu * 30
                d2["Index"] = str(GG)
                d2["PlateID"] = str(板块代码)
                # time.sleep(5)
                rep2 = requests.post(url1, headers=hd, data=d2, verify=False)
                GG_data = json.loads(rep2.text)
                if not GG_data['list']:  # 如果list列表为空
                    break  # 跳出循环

                # print(GG_data)
                for idx2, item2 in enumerate(GG_data['list'], start=1):
                    股票代码 = item2[0] if item2[0] else 0
                    股票名称 = item2[1] if item2[1] else 0
                    价格 = item2[5] if item2[5] else 0
                    涨幅 = item2[6] if item2[6] else 0
                    板块细分 = item2[4] if item2[4] else 0
                    小细分 = item2[39] if item2[39] else 0
                    领涨次数 = item2[40] if item2[40] else 0
                    连板数 = item2[23] if item2[23] else 0
                    龙序 = item2[24] if item2[24] else 0
                    人气值 = item2[58] if item2[58] else 0
                    实际流通 = item2[10] if item2[10] else 0
                    流通市值 = item2[38] if item2[38] else 0
                    收盘封单 = item2[28] if item2[28] else 0
                    最大封单 = item2[29] if item2[29] else 0
                    G300W净额 = item2[50] / 1000000000 if item2[50] else 0
                    plate_stocks["板块名称"] = 板块名称
                    plate_stocks = pd.concat([plate_stocks, pd.DataFrame(
                        {"股票代码": [股票代码], "股票名称": [股票名称], "价格": [价格], "涨幅": [涨幅],
                         "板块细分": [板块细分]})])

            mid_stocks = pd.concat([mid_stocks, plate_stocks])
            print(mid_stocks)
            # 将当前板块的个股数据保存到all_stocks中
        all_stocks = pd.concat([all_stocks, mid_stocks])

    return all_stocks


def main():
    # with ThreadPoolExecutor(9) as t:
    #     results = t.map(fetch_data, range(9))
    results = fetch_data(0)
    #all_stocks = pd.concat(results)

    sheet_data = {}
    for plate_name, plate_data in results.groupby('板块名称'):
        sheet_data[plate_name] = plate_data
        # print(sheet_data)
    with pd.ExcelWriter(save_path_cs, engine='openpyxl') as writer:
        for sheet_name, data in sheet_data.items():
            data.to_excel(writer, sheet_name=sheet_name, index=False)


if __name__ == '__main__':
    #main()
    search = '市值>15'
    search = re.split('>|<', search)[1]
    print(search)



